<?php

namespace app\api\controller\integral;

use app\api\controller\AuthController;
use app\api\service\IntegralOrderService;
use app\api\service\IntegralService;
use app\api\service\OrderService;
use app\api\service\PaymentService;
use think\exception\ValidateException;
use think\facade\Queue;

class OrderController extends AuthController
{

    /**
     * 生成订单
     * */
    public function save()
    {
        $param = $this->request->param();

        try{
            validate('IntegralOrderValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0,'msg' => $e->getError()]);
        }

        if (!empty($param['integral_goods_id'])){
            $goods = IntegralOrderService::findSingleIntegralGoods($param['integral_goods_id']);
        }

        if (!empty($param['sku_id'])){
            $goods =  IntegralOrderService::findManyIntegralGoods($param['sku_id']);
        }

        if (empty($goods)){
            return json(['code' => 0,'msg' => '商品已下架']);
        }

        $param['buy_num'] = isset($param['buy_num']) ? $param['buy_num'] : 1;

        if ($goods['redeem_stock']< $param['buy_num']){
            return json(['code' => 0,'msg' => '库存不足']);
        }

        $user_id = $this->request->user['user_id'];

        $user_integral = IntegralService::getUserIntegral($user_id);

        $total_integral = $goods['redeem_integral']* $param['buy_num'];

        if ($user_integral<$total_integral){
            return json(['code' => 0,'msg' => '对不去,您的积分不足!']);
        }

        if ($goods['spec_type'] ==1){
            $goods['image'] = $goods['main_image'];
        }

        if ($goods['spec_type'] ==2){
            $goods['image'] = !empty($goods['image']) ? $goods['image'] : $goods['main_image'];
        }

        $real_amount = 0;
        if($goods['redeem_price']>0){
            $real_amount = number_format($goods['redeem_price']*$param['buy_num'],2);
        }

        $redeem_integral = $goods['redeem_integral']*$param['buy_num'];

        $order_no = PaymentService::generateOrderNum();
        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($param,$goods,[
            'user_id' => $user_id,
            'order_type' => 3,
            'real_amount' => $real_amount,
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'market_price' => $goods['sell_price'],
            'sell_price' => $goods['redeem_price'],
        ]);


        /**
         * 保存订单信息
         * */
        $result = OrderService::saveOrder($data);

        if ($result === false){
            return  json(['code' =>0, 'msg'=> '下单失败!']);
        }

        if ($real_amount == 0){
            $result =  Queue::push('app\store\job\Account@integral',[
                'user_id' => $user_id,
                'desc' => '积分兑换商品',
                'change_type'=> 2,
                'integral' => $redeem_integral
            ],'userAccount');
            OrderService::changeOrder($out_trade_no,time());
            if ($result){
                return  json(['code' =>1, 'is_pay' => 'no', 'data' => ['order_no' => $order_no],'msg' =>'兑换成功!']);
            }

            return  json(['code' =>0,'msg' => '兑换失败!']);
        }

        $config = PaymentService::findPaymentConfig($param['store_id'],$param['payment_type']);

        if (empty($config)){
            return  json(['code' =>0, 'msg' =>'支付异常!']);
        }

        $payment_data = [
            'config' => $config,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount,
        ];

        if ($data['payment_type'] == 1){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/wx/notify';
        }

        if ($data['payment_type'] == 2){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/ali/notify';
        }

        $prepay_info = PaymentService::createOrder($payment_data);

        if (!empty($prepay_info)){
            return json([
                'code' =>1,
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'prepay_info' => $prepay_info
                ],
                'msg' => '下单成功!'
            ]);
        }

        return  json(['code' =>0, 'msg' => '下单失败!']);
    }
}